package psd.model.Prolog.Converters;

import java.util.List;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;

import psd.model.IConverter;
import psd.model.Prolog.FactGenerationToolbox;
import psd.model.Prolog.PrologConverter;


public class PrologVariableDeclarationStatementConverter extends
PrologConverter implements IConverter<VariableDeclarationStatement>{

	public PrologVariableDeclarationStatementConverter(
			FactGenerationToolbox toolbox) {
		super(toolbox);
	}

	@Override
	public boolean convert(VariableDeclarationStatement node) {
	    List fragments = node.fragments();
        int mods = node.getModifiers();
        for(int i = 0; i < fragments.size(); i++)
        {
            VariableDeclarationFragment fragment = (VariableDeclarationFragment)fragments.get(i);
            VariableDeclarationFragment theNode = fragment;
            ASTNode theParent = theNode.getParent().getParent();
            ASTNode theEnc = getEnclosingNode(theNode);
            String typeTerm;
            if(theNode.resolveBinding() == null)
            {
                typeTerm = "resolve_failed";
            } else
            {
                ITypeBinding theType = theNode.resolveBinding().getType();
                typeTerm = typeResolver.getTypeTerm(theType);
            }
            String theName = (new StringBuilder("'")).append(theNode.getName().getIdentifier()).append("'").toString();
            Expression theInitializer = theNode.getInitializer();
            String args[] = {
                idResolver.getID(theNode), idResolver.getID(theParent), idResolver.getID(theEnc), typeTerm, theName, idResolver.getID(theInitializer), this.getFilePath(node), this.getLineNumber(node)
            };
            writer.writeFact("localDefT", args);
            writer.writeFact("slT", new String[] {
                idResolver.getID(theNode), Integer.toString(theNode.getStartPosition()), Integer.toString(theNode.getLength()), this.getFilePath(node), this.getLineNumber(node)
            });
            checkAndGenComments(node, idResolver.getID(fragment));
            writeSourceLocationArgumentIdentifier(fragment, fragment.getName(), node.modifiers());
            writeModifiers(theNode, mods);
        }

        return true;
	}

}
